
package eg.ci.mvn.service.demo.controller;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import eg.ci.mvn.service.api.constant.ApiNo;
import eg.ci.mvn.service.api.model.BaseResponse;
import eg.ci.mvn.service.api.model.ErrorType;
import eg.ci.mvn.service.api.model.param.MqParam;
import eg.ci.mvn.service.core.config.rabbitmq.MqTestRabbitFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.RabbitListenerEndpointRegistry;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Mq
 */
@Slf4j
@RestController
@RequestMapping(value = "demo/mq")
@Tag(name = ApiNo.DEMO_MQ)
public class MqController {

    @Resource
    private RabbitListenerEndpointRegistry registry;

    /**
     * 开启监听
     */
    @Operation(summary = ApiNo.DEMO_MQ_START, description = ApiNo.DEMO_MQ_START)
    @GetMapping("/start")
    public void start() {
        registry.start();

        for (MessageListenerContainer container: registry.getListenerContainers()) {
            // 判断监听容器是否启动，未启动则将其启动
            if (!container.isRunning()) {
                log.info("start  ");
                container.start();
            }
//            // 将其恢复
//            container.resume();
        }
    }

    /**
     * 停止监听
     */
    @Operation(summary = ApiNo.DEMO_MQ_STOP, description = ApiNo.DEMO_MQ_STOP)
    @GetMapping("/stop")
    public void stop() {
        registry.start();

        for (MessageListenerContainer container: registry.getListenerContainers()) {
            // 判断监听容器是否启动，启动则将其停止
            if (container.isRunning()) {
                log.info("stop  ");
                container.stop();
            }
        }
    }


    @Operation(summary = ApiNo.DEMO_MQ_SEND, description = ApiNo.DEMO_MQ_SEND)
    @PostMapping(value = "send")
    public BaseResponse send(@RequestBody MqParam.MqRequestParam request) {
        //
        RabbitTemplate rabbitTemplate = SpringUtil.getBean(MqTestRabbitFactory.BEAN_NAME_RABBIT_TEMPLATE, RabbitTemplate.class);
        rabbitTemplate.convertAndSend(
                request.getExchange(),
                request.getRoutingKey(),
                JSON.parseObject(request.getJsonString()),
                new CorrelationData()
        );

        return new BaseResponse<>(ErrorType.SUCCESS);
    }

}
